from app.exts import mysql_pool
from app.utils import date_util
from datetime import datetime

mapping = {
    "HanfanVComponent": {"table": "hanfan_new_predict",
                         "key": "DATE_TIME"},
    "HanFan": {"table": "hanfan_new_predict",
               "key": "DATE_TIME"},
    "HanfanData": {"table": "hanfan_new_predict",
                   "key": "DATE_TIME"},
    "LuzhaComponent": {"table": "luzha_predict_po",
                       "key": "DATE_TIME"},
    "LuGang": {"table": "cg_lt_gl04_lugang_data",
               "key": "date_time"},
    "LuGangQinShiResult": {"table": "cg_lt_gl04_lugang_qinshi_result",
                           "key": "date_time"},
    "LuGangQinShiData": {"table": "cg_lt_gl04_lugang_qinshi_data",
                         "key": "date_time"},
    "LuGangPredict": {"table": "cg_lt_gl04_lugang_activiness_predict_result",
                      "key": "date_time"},
    "GaoLu": {"table": "cg_lt_gl_gl04_gaolu_predict",
              "key": "DateTime"},
    "GaoLuDiagnoseScore":{"table": "gaolu_diagnose_score",
              "key": "date_time"},
    "GaoLuDiagnoseCount":{"table": "gaolu_diagnose_count",
              "key": "date_time"},
    "ShaoJie":{
        "table":"cg_sj_sjj_sj02_predict",
        "key": "gmt_create",
    },"ExpertScore":{
        "table":"gaolu_diagnose_data",
        "key": "date_time"
    }

}


def get_latest_time(item_name):
    table_info = mapping.get(item_name, None)
    if table_info is None:
        return date_util.get_start_of_day(datetime.now()), \
            date_util.get_end_of_day(datetime.now()), \
            datetime.now()

    conn, cursor = mysql_pool.connect(db='ironman')
    table_name = table_info['table']
    time_key = table_info['key']
    cursor.execute("select {} from {} order by {} desc limit 1"
                   .format(time_key, table_name, time_key))
    record = cursor.fetchone()
    if record and record.get(time_key,None):
        time = record[time_key]
        return date_util.get_start_of_day(time), \
            date_util.get_end_of_day(time), \
            time
    return date_util.get_start_of_day(datetime.now()), \
        date_util.get_end_of_day(datetime.now()), \
        datetime.now()
